from flask import Blueprint, Response, request
from bs4 import BeautifulSoup
import requests
import re
from cache import cache

google_fonts_base_url = "https://fonts.googleapis.com/"
google_fonts_proxy = Blueprint('google_fonts_proxy', __name__)

@google_fonts_proxy.route('/google-fonts/<path:subpath>')
@cache.cached(timeout=3600)  # Cache for 1 hour
def google_fonts(subpath):
    # Construct the full URL
    full_url = f"{google_fonts_base_url}{subpath}"

    # Get the content from the target URL
    response = requests.get(full_url, headers={"Accept-Encoding": "identity"})

    # Copy all response headers
    headers = {key: value for key, value in response.headers.items()}
    headers['Transfer-Encoding'] = 'identity'

    # Parse HTML content and modify links if the content is HTML
    content = response.content
    if response.headers.get('content-type', '').startswith('text/html'):
        soup = BeautifulSoup(content, 'html.parser')
        for link in soup.find_all('a', href=True):
            href = link['href']
            # If the link is not an absolute URL and not a javascript link
            if not re.match(r'^[a-z]+://', href) and not href.startswith('javascript:'):
                link['href'] = f"/google-fonts{href}"

        content = str(soup)

    return Response(content, status=response.status_code, headers=headers, content_type=response.headers['content-type'])
